<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>监听localstorage变化（同业面）</title>
</head>

<body>
    <button class="add">add</button>
    <button class="add1">add1</button>
    <button class="del">del</button>

    <script>
        var log = console.log

        function watchLocalStorageAdd() {
            var orignalSetItem = localStorage.setItem;
            localStorage.setItem = function (key, newValue) {
                var setItemEvent = new Event('setItemEvent')
                setItemEvent.key = key
                setItemEvent.newValue = newValue
                window.dispatchEvent(setItemEvent)
                orignalSetItem.apply(this, arguments)
            }

            window.addEventListener('setItemEvent', function (e) {
                if (e.key === 'demo') {
                    var _this = localStorage.getItem('demo')
                    if (_this !== e.newValue) {
                        log('key值为demo的值发生改变,之前是' + _this + '当前为' + e.newValue)
                    } else {
                        log('key值为demo值' + e.newValue)
                    }
                }
            })

            document.querySelector('.add').addEventListener('click', function () {
                localStorage.setItem("demo", "123");
            })

            document.querySelector('.add1').addEventListener('click', function () {
                localStorage.setItem("demo", "111");
            })
        }

        function watchLocalStorageRemove() {
            var orignalremoveItem = localStorage.removeItem;
            localStorage.removeItem = function (key, newValue) {
                var removeItemEvent = new Event("removeItemEvent");
                removeItemEvent.key = key;
                removeItemEvent.newValue = newValue;
                window.dispatchEvent(removeItemEvent);
                orignalremoveItem.apply(this, arguments);
            };

            window.addEventListener("removeItemEvent", function (e) {
                if (localStorage.getItem("demo")) {
                    if (e.key == 'demo') {
                        log("key值为demo，删除成功");
                    }
                } else {
                    log("本地数据无key值为demo")
                }
            });
            
            document.querySelector('.del').addEventListener('click', function () {
                localStorage.removeItem("demo");
            })
        }

        watchLocalStorageAdd()
        watchLocalStorageRemove()
    </script>
</body>

</html>